package com.nowcoder;

import lombok.SneakyThrows;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.*;

public class JDKTask {
    static final Logger logger = LoggerFactory.getLogger(JDKTask.class);
    // 普通线程池
    ExecutorService executorService = Executors.newFixedThreadPool(5);

    void sleep(Long m) throws InterruptedException {
        Thread.sleep(m);
    }

    @Test
    void test1() throws InterruptedException {
        Runnable task = new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                logger.debug("Hello");
                sleep(1000L);
            }
        };
        for(int i = 0; i < 10; i++) {
            executorService.submit(task);
        }
        sleep(10000L);
    }

    // 定时任务线程池
    ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(5);
    @Test
    void test2() throws InterruptedException {
        Runnable task = new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                logger.debug("Hello Task");
                sleep(1000L);
            }
        };
        // 等待5秒才开始，每2秒执行一次这个任务
        scheduledExecutorService.scheduleAtFixedRate(task, 5, 2, TimeUnit.SECONDS);
        sleep(10000L);
    }
}
